package com.zlkj.pro.core.util;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 孙铭泽
 * @date 2022/10/22
 * @time 11:17
 */

public class ExcelExportUtil {

    /**
     * @GetResource(name = "表格导出", path = "/export")
     * public void export() throws IOException {
     * <p>
     * }
     */
    public static void export(List<?> exportSourceList, LinkedHashMap<String, String> headerAlias, String fileName) throws IOException {
        HttpServletResponse response = HttpServletUtil.getResponse();
        ExcelWriter writer = ExcelUtil.getWriter(Boolean.TRUE);
        for (Map.Entry<String, String> alias : headerAlias.entrySet()) {
            writer.addHeaderAlias(alias.getKey(), alias.getValue());
        }
        writer.write(exportSourceList, Boolean.TRUE);
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream, Boolean.TRUE);
        outputStream.close();
        writer.close();
    }
}
